package org.dbpt.performance;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadItem extends ContainerItem {
	private int threadCount = 1;
	private ExecutorService executorService = Executors.newFixedThreadPool(10);

	public int getThreadCount() {
		return threadCount;
	}

	public void setThreadCount(int threadCount) {
		this.threadCount = threadCount;
	}

	public ExecutorService getExecutorService() {
		return executorService;
	}

	public void setExecutorService(ExecutorService executorService) {
		this.executorService = executorService;
	}

	public ThreadItem() {
		super();
	}

	public ThreadItem(DBPTItem child1, DBPTItem child2, DBPTItem child3) {
		super(child1, child2, child3);
	}

	public ThreadItem(DBPTItem child1, DBPTItem child2) {
		super(child1, child2);
	}

	public ThreadItem(DBPTItem child) {
		super(child);
	}

	public ThreadItem(List<DBPTItem> children) {
		super(children);
	}

	@Override
	public void doIteration() {
		final AtomicInteger counter = new AtomicInteger(threadCount);
		for(int i = 0; i < threadCount; i++) {
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					ThreadItem.super.doIteration();
					counter.decrementAndGet();
					synchronized (ThreadItem.this) {
						ThreadItem.this.notify();
					}
				}				
			});
		}
		while(counter.get() != 0) {
			synchronized (this) {
				try {
					wait(10);
				} catch (InterruptedException e) {
					// Logs the warning
					e.printStackTrace();
				}
			}
		}
			
	}
	

}
